/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-08-09 03:26:10
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-08-10 21:36:51
 * @Description : 初始化 ol
 */
import { delGis } from '@ol/api'
import { getDefaultOptions } from '@ol/defaultOptions'
import { type GisKey, type GisRef, Platform } from '@ol/define'
import type { IViewerOptionsOl } from '@ol/types'
import { Projections } from '@ol/utils'
import { isString } from 'es-toolkit'
import { isElement } from 'es-toolkit/compat'

import Map from 'ol/Map'
import Viewer from 'ol/View.js'
import { defaults } from 'ol/interaction/defaults'

// 使用者自行导入
//import 'ol-ext/dist/ol-ext.min.css'
//import 'ol/ol.css'

export default function initMap(
  container: HTMLElement | string,
  viewerOptions: IViewerOptionsOl,
  key: GisKey,
): GisRef {
  const map = new Map({
    target: container,
    view: new Viewer({
      zoom: viewerOptions.zoom,
      maxZoom: viewerOptions.maxZoom,
      minZoom: viewerOptions.minZoom,
      center: viewerOptions.center,
      extent: viewerOptions.extent,
      projection: Projections.get(viewerOptions.projection),
    }),
    interactions: defaults({ doubleClickZoom: false }),
  })

  const target = map.getTarget()
  let targetDOM = null

  if (isElement(target)) {
    targetDOM = target
  } else if (isString(target)) {
    targetDOM = document.querySelector(`#${target}`)
  }

  let _bgUrl = getDefaultOptions('bgUrl')
  const { bgUrl } = viewerOptions
  if (bgUrl && isString(bgUrl)) {
    _bgUrl = bgUrl
  }

  if (isElement(targetDOM) && bgUrl !== false) {
    // @ts-ignore
    targetDOM.style.backgroundImage = `url('${_bgUrl}')`
  }

  const obj = {
    key,
    config: viewerOptions,
    cache: {},
    basemap: { name: null },
    platform: Platform.OL,
    projection: viewerOptions.projection,
    map,
    dispose: () => {
      //map.setTarget()
      //delGis(key)
      map.setTarget()
      return new Promise((resolve) => {
        queueMicrotask(() => {
          delGis(key)
          console.log('disposed map')
          resolve(true)
        })
      })
    },
  } as GisRef
  console.log('viewerOptions', viewerOptions)
  return Object.freeze(obj)
}
